<?php

namespace App\Http\Service\Brand;

use App\Models\Brandmapping;
use App\Http\Service\BaseService;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;


class BrandmappingService  extends BaseService
{
    private $model;

    public function __construct(Brandmapping $model)
    {
        parent::__construct();
        $this->model = $model;
       
    }
   
    /**
     *
     * @param array $params
     * @return array
     */
    public function addData($request,$data=[])
    {
        $original_name=$data['original_name'];
        $standard_name=$data['standard_name'];
        $list = [
            "其它品牌", 
            "其它",
            "其他家", 
            "其他品牌",
            "其他",
            "未知", 
            "", 
            "无",
            'others/其他'
           ];
        if (in_array($original_name,$list) || in_array($standard_name,$list)){
            $original_name= "未知品牌";
        }
        $first=$this->model->where(['original_name'=>$original_name])->first();
        if($first){
            $standard_name_arr=explode('/', $first['standard_name']);
            $standard_name_arr[]=$standard_name;
            $standard_name_arr=array_unique($standard_name_arr);
            $standard_name_str=implode('/', $standard_name_arr);
            $multiple_flag = 0;
            if (count($standard_name_arr) >1){
                $multiple_flag = 1;
            }
            $data1=[
                'standard_name'=>$standard_name_str,
                'multiple_flag'=>$multiple_flag
            ]; 
            $this->model->where(['original_name'=>$original_name])->update($data1);

        }else{
            $data2=[
                'original_name'=>$original_name,
                'standard_name'=>$standard_name,
                'multiple_flag'=>0,
                'error'=>0
            ];
            
            $res=$this->model->insertGetId($data2);
        }

        $this->success1();
        
    }

    #根据平台返回的品牌获取目标品牌
    public function targetBrand88888888($original_name)
    {
        $first=$this->model->where(['original_name'=>$original_name])->first();
        $result="未知";
        if(empty($original_name)){
            return $result;
        }
        if(!$first){
            $data=[
                'original_name'=>$original_name,
                'standard_name'=>$original_name,#品牌不存在和原始品牌一样
            ];
            #判断是否要写入
            $first2=$this->model->where($data)->first();
            if(!$first2){
                $data['status']=1;
                $data['update_time']=date("Y-m-d H:i:s");
                $data['create_time']=date("Y-m-d H:i:s");
                $this->model->insertGetId($data);
            }
            $result=$original_name;
        }else{
            $result=$first['standard_name'];
        }
        return $result;
    }

    public function targetBrand($original_name)
    {
        if (empty($original_name)) {
            return "未知";
        }
        
        $cacheKey = 'brand_mapping:' . md5($original_name);
        
        // 尝试从缓存获取
        $cachedResult = cache()->get($cacheKey);
        if ($cachedResult !== null) {
            return $cachedResult;
        }
        
        // 使用缓存锁防止缓存击穿
        $lockKey = 'brand_lock:' . md5($original_name);
        $lock = cache()->lock($lockKey, 10);
        
        try {
            // 再次检查缓存（在获取锁期间可能已被其他进程填充）
            $cachedResult = cache()->get($cacheKey);
            if ($cachedResult !== null) {
                return $cachedResult;
            }
            
            if ($lock->get()) {
                // 查询数据库
                $existing = $this->model->where('original_name', $original_name)->first();
                
                if ($existing) {
                    $result = $existing->standard_name;
                } else {
                    // 插入新记录
                    $data = [
                        'original_name' => $original_name,
                        'standard_name' => $original_name,
                        'status' => 1,
                        'update_time' => date("Y-m-d H:i:s"),
                        'create_time' => date("Y-m-d H:i:s")
                    ];
                    
                    try {
                        $this->model->insertGetId($data);
                        $result = $original_name;
                    } catch (\Exception $e) {
                        // 处理重复插入
                        if (str_contains($e->getMessage(), 'Duplicate')) {
                            $existing = $this->model->where('original_name', $original_name)->first();
                            $result = $existing ? $existing->standard_name : $original_name;
                        } else {
                            $result = $original_name;
                        }
                    }
                }
                
                // 写入缓存
                cache()->put($cacheKey, $result, 3600);
                $lock->release();
                
                return $result;
            } else {
                // 获取锁失败，等待后重试或返回默认值
                usleep(100000); // 等待100ms
                return cache()->get($cacheKey, $original_name);
            }
            
        } catch (\Exception $e) {
            if (isset($lock)) {
                $lock->release();
            }
            \Log::error('品牌映射查询失败: ' . $e->getMessage());
            return $original_name;
        }
    }
}
